import React, {Component} from 'react';
import PubSub from 'pubsub-js';
import './index.css';

export default class List extends Component {
	state = { //初始化状态
		users:[], //users初始值为数组
		// isFirst:true, //是否为第一次打开页面
		isLoading:false,//标识是否处于加载中
		err:'',//存储请求相关的错误信息
	}

	// 组件挂载完毕后加载
	componentDidMount(){
		this.token = PubSub.subscribe('wgy',(_,stateObj)=>{
			this.setState(stateObj)
		})
	}

	// 组件将要卸载
	componentWillUnmount(){
		// 删除订阅
		PubSub.unsubscribe(this.token)
	}

	render() {
		const {users, isLoading, err} = this.state;

		return (
			<div className="row">
				{isLoading ? (
					<h1>加载中...</h1>
				) : err ? (
					<h1 style={{color: 'red'}}>请求错误</h1>
				) : (
					users.map(item => {
						return (
							<div className="card" key={item.id}>
								<a rel="noreferrer" href={item.html_url} target="_blank">
									<img
										alt="head portrait"
										src={item.avatar_url}
										style={{width: '100px'}}
									/>
								</a>
								<p className="card-text">{item.login}</p>
							</div>
						);
					})
				)}
			</div>
		);
	}
}
